package com.csair.seam.infrastructure.exception;

import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.csair.seam.infrastructure.web.BaseResponse;
import com.csair.seam.infrastructure.web.ResponseCode;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @Author: wurunbin
 * @Date: 2020/3/5 14:16
 * @Description:
 **/
@RestControllerAdvice
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public BaseResponse<String> handleBizException(BizException e){
    	log.error(e.getMessage(), e);
        return new BaseResponse<>(ResponseCode.BIZ_LIMIT,e.getMessage());
    }

    @ExceptionHandler(AuthException.class)
    @ResponseBody
    public BaseResponse<String> handleAuthException(AuthException e){
        return new BaseResponse<>(ResponseCode.NO_PERMISSION,e.getMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public BaseResponse<String> maxUploadSizeExceededException(MaxUploadSizeExceededException e){
        log.error(e.getMessage(), e);
        log.error("文件过大");
        return new BaseResponse<>(ResponseCode.ERROR,"上传文件、10M文件过大");
    }

    @ExceptionHandler
    @ResponseBody
    public BaseResponse<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        String message = bindingResult.getFieldError().getDefaultMessage();
        return new BaseResponse<>(ResponseCode.PARAM_ERROR,message);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResponse<String> handleException(Exception e){
        log.error(e.getMessage(), e);
        return new BaseResponse<>(ResponseCode.ERROR,"系统异常");
    }
}
